// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import 'font-awesome/css/font-awesome.css'
import axios from 'axios'
import Token from './token'

Vue.use(ElementUI);

Vue.config.productionTip = false;

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>',
  created() {
    if (process.env.BASE_API_URL.indexOf('https:') === 0 && location.protocol !== 'https:') {
      location.href = location.href.replace(/^http/, 'https')
    }

    axios.defaults.baseURL = process.env.BASE_API_URL;
    //axios.defaults.withCredentials = true;

    axios.interceptors.request.use(config => {
      const token = Token.get();
      token && (config.headers['Token'] = token);
      return config;
    });

    axios.interceptors.response.use(response => {
      if (typeof response.data.code !== "undefined") {
        if (response.data.code !== 0) {
          if (response.data.code === 4001) {
            this.$router.push(response.data.data.redirect);
          } else {
            let message = response.data.message;
            response.data.code !== 1 && (message += '(' + response.data.code + ')');
            this.$message.error(message);
          }
          return Promise.reject(response.data)
        } else {
          return response.data.data;
        }
      }
      return response;
    }, error => {
      this.$notify({
        title: '错误',
        message: error.toString(),
        type: 'error',
      });
      return Promise.reject(error);
    });
  }
});
